﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Asteroids.Game;

namespace Asteroids
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static DispatcherTimer Timer { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Instance = this;

            Timer = new DispatcherTimer(DispatcherPriority.Background, Dispatcher)
                        {
                            Interval = TimeSpan.FromMilliseconds(33)
                        };

            Timer.Tick += (sender, args) =>
                              {
                                  try
                                  {
                                      Game.Game.Instance.Update();
                                  } catch(Exception e)
                                  {
                                      MessageBox.Show("Sorry, something broke...", "Oops.", MessageBoxButton.OK,
                                                      MessageBoxImage.Error);
                                      Console.WriteLine(e.Message);
                                      Environment.Exit(9001);
                                  }
                              };

            Game.Game.Instance.NextLevelEvent += ShowNextLevelScreen;
            Game.Game.Instance.Player.OnPlayerDeath += ShowGameOverScreen;
        }

        public static MainWindow Instance { get; private set; }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (KeyDownEvent != null)
                KeyDownEvent(sender, e);
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (KeyUpEvent != null)
                KeyUpEvent(sender, e);
        }

        public void ShowNextLevelScreen(int level)
        {
            Game.Game.Instance.IsPaused = true;
            Instance.NextLevelUC.Visibility = Visibility.Visible;

            ticks = 60;
            Timer.Tick += DuringNextLevelScreen;
        }

        private int ticks;
        private void DuringNextLevelScreen(object s, EventArgs e)
        {
            if (--ticks != 0)
                return;
            Instance.NextLevelUC.Visibility = Visibility.Hidden;
            Game.Game.Instance.IsPaused = false;
            Timer.Tick -= DuringNextLevelScreen;
        }

        public void ShowGameOverScreen(object sender, EventArgs e)
        {
            Game.Game.Instance.Shutdown();
            GameScreenUC.Visibility = Visibility.Hidden;
            GameOverUC.Visibility = Visibility.Visible;
        }

        public delegate void KeyDel(object sender, KeyEventArgs e);
        public new static event KeyDel KeyUpEvent;
        public new static event KeyDel KeyDownEvent;
    }
}
